package com.feel.easycloud.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.*;

public class AuthenticateUtils {

    private static Map<String, Object> headerClaims = new HashMap<>();
    static {
        headerClaims.put("typ", "JWT");
        headerClaims.put("alg", "HS256");
    }

    /**
     * 创建jwt
     * @param data
     * @return
     */
    public static String createJWT(Map<String, String> data) {
        data.put("tokenVerison",System.currentTimeMillis() + "");
        JWTCreator.Builder builder = JWT.create().withHeader(headerClaims);
        Set<Map.Entry<String, String>> entrySet = data.entrySet();
        for (Map.Entry<String, String> entry : entrySet) {
            builder.withClaim(entry.getKey(), entry.getValue());
        }
        Calendar expiredTime = Calendar.getInstance();
        expiredTime.add(Calendar.SECOND, 1800);//默认过期时间 60秒

        try {
            return builder
                    // 过期时间
                    .withExpiresAt(expiredTime.getTime())
                    // 创建时间
                    .withIssuedAt(new Date())
                    // 签名
                    .sign(Algorithm.HMAC256("easycloud"));//密钥
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * 校验jwt
     * @param token
     * @return
     */
    public static Map<String, Claim> verfiyJWT(String token) {
        JWTVerifier verifier = null;
        try {
            verifier = JWT.require(Algorithm.HMAC256("easycloud")).build();
        } catch (Exception e) {
        }

        DecodedJWT jwt = null;
        try {
            jwt = verifier.verify(token);
        }
        catch (TokenExpiredException e) {
        }
        catch (Exception e) {
        }

        return jwt.getClaims();
    }



}
